package com.jinhao.crowd.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jinhao.crowd.entity.Role;
import com.jinhao.crowd.entity.RoleExample;
import com.jinhao.crowd.exception.RoleNameRepeatException;
import com.jinhao.crowd.mapper.RoleMapper;
import com.jinhao.crowd.service.api.RoleService;
import com.jinhao.crowd.util.CrowdConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created on 2020/10/20.
 *
 * @author Valar Morghulis
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 对角色表进行查询并分页
     */
    @Override
    public PageInfo<Role> getPageInfo(Integer pageNum, Integer pageSize, String keyword) {

        PageHelper.startPage(pageNum, pageSize);

        List<Role> roles = roleMapper.selectRoleByKeyword(keyword);

        return new PageInfo<>(roles);
    }


    /**
     * 新增角色
     *
     * @param role
     */
    @Override
    public void saveRole(Role role) {

        // 获取RoleExample对象
        RoleExample roleExample = new RoleExample();

        // 创建规范
        RoleExample.Criteria criteria = roleExample.createCriteria();
        String name = role.getName();
        criteria.andNameEqualTo(name);

        // 查询要插入的角色名是否已经存在
        List<Role> roles = roleMapper.selectByExample(roleExample);
        if (roles == null || roles.size() == 0) {
            // 不存在则执行插入语句
            roleMapper.insert(role);
        } else {
            // 已经存在，就抛出已存在的异常
            throw new RoleNameRepeatException(CrowdConstant.MESSAGE_ROLENAME_REPEAT);
        }
    }

    /**
     * 修改角色名称
     *
     * @param role
     */
    @Override
    public void updateRole(Role role) {
        try {
            roleMapper.updateByPrimaryKey(role);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RoleNameRepeatException(CrowdConstant.MESSAGE_ROLENAME_REPEAT);
        }
    }


    /**
     * 根据角色id数组，删除角色
     *
     * @param roleIdArray
     */
    @Override
    public void removeRoleById(Integer[] roleIdArray) {
        for (Integer roleId : roleIdArray) {
            roleMapper.deleteByPrimaryKey(roleId);
        }
    }

    @Override
    public List<Role> getAssignedRoles(Integer adminId) {

        return roleMapper.selectAssignedRoles(adminId);
    }

    @Override
    public List<Role> getUnAssignedRoles(Integer adminId) {
        return roleMapper.selectUnAssignedRoles(adminId);
    }
}
